package com.longge;

import java.util.ArrayList;

public class ReorderSpaces {

    public String reorderSpaces(String text) {

        char[] chars = text.toCharArray();
        int tabCount = 0;
        for (char aChar : chars) {
            if (aChar == ' ') {
                tabCount++;
            }
        }
        String[] s = text.split(" ");
        ArrayList<String> strs = new ArrayList<>();
        for (String s1 : s) {
            if (!s1.equals("")) {
                strs.add(s1);
            }
        }
        int size = 0, lastSize = 0;
        if (strs.size() > 1) {
            size = tabCount / (strs.size() - 1);
            lastSize = tabCount - size*(strs.size() - 1);
        } else {
            lastSize = tabCount;
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < strs.size(); i++) {
            String str = strs.get(i);
            sb.append(str);
            int temp = size;
            while (temp > 0 && i != strs.size() - 1) {
                sb.append(" ");
                temp--;
            }
            if (i == strs.size() - 1) {
                while (lastSize > 0) {
                    sb.append(" ");
                    lastSize--;
                }
            }

        }
        return sb.toString();

    }

    public static void main(String[] args) {
        new ReorderSpaces().reorderSpaces(" practice   makes   perfect");
    }
}
